package com.semeureka.frame.util;

import java.io.UnsupportedEncodingException;

import javax.xml.bind.DatatypeConverter;

public class PduUtils {
	public static String decodeBit7Hex(String bit7Hex, int len) {
		byte[] bit7 = DatatypeConverter.parseHexBinary(bit7Hex);
		StringBuffer bit8Hex = new StringBuffer(len);
		int bits = 0;
		for (int i = 0, k = 0; i < bit7.length; i++, k++) {
			bits = (bits >> 7) | ((bit7[i] & 0xFF) << k);
			bit8Hex.append((char) (bits & 0x7F));
			if (k == 6) {
				k = -1;
				bits = bits >> 7;
				bit8Hex.append((char) (bits & 0x7F));
			}
			if (bit8Hex.length() == len) {
				return bit8Hex.toString();
			}
		}
		return bit8Hex.toString();
	}

	public static String decodeUcs2Hex(String ucs2Hex) {
		byte[] ucs2 = DatatypeConverter.parseHexBinary(ucs2Hex);
		try {
			return new String(ucs2, "UTF-16BE");
		} catch (UnsupportedEncodingException e) {
			return null;
		}
	}

	public static String exchange(String source) {
		char[] cs = source.toCharArray();
		for (int i = 0; i < cs.length; i = i + 2) {
			char c = cs[i];
			cs[i] = cs[i + 1];
			cs[i + 1] = c;
		}
		return new String(cs);
	}
}
